//
//  DPTubeNetwork.m
//  NetworkStatus
//
//  Created by Joel Parsons on 21/11/2011.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "DPTubeNetwork.h"

@implementation DPTubeNetwork

@synthesize currentTubeLine, tubeLineArray, tubeLineDictionary;


-(BOOL)getTubeLineStatus{
    tubeLineArray = [[NSMutableArray alloc] init];
    
    NSURL * dataURL = [NSURL URLWithString:@"http://joelparsons.net/networkStatus.xml"];
    
    NSXMLParser * XMLParser = [[NSXMLParser alloc] initWithContentsOfURL:dataURL];
    
    //by becoming the delegate of the parser we get referred the delegate messages below
    XMLParser.delegate = self;
    
    BOOL success = [XMLParser parse];
    
    if (success) {
        //we put the tube line objects in a dictionary as the model should have no concept of 
        //what order the objects are displayed. 
        
        self.tubeLineDictionary = [[NSMutableDictionary alloc] initWithCapacity:tubeLineArray.count];
        for (DPTubeLine * aTubeLine in self.tubeLineArray) {
            [self.tubeLineDictionary setObject:aTubeLine forKey:aTubeLine.name];
        }
    }

    return success;
}

//This method gets called for every opening XML tag
//As the parser is procedural this will get called multiple times before the closing method is called
//We check for the opening tag of all the elements we are interested in.

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    
    //we know from the API reference that this is the first element for every line
    //so we create our tube line object here and start filling in details.
    if ([elementName isEqualToString:@"LineStatus"]) {
        self.currentTubeLine = [[DPTubeLine alloc] init];
        NSString * statusDetails = [attributeDict objectForKey:@"StatusDetails"];
        self.currentTubeLine.statusDetails = statusDetails;
    }
    
    if ([elementName isEqualToString:@"Line"]) {
        NSString * lineName = [attributeDict objectForKey:@"Name"];
        self.currentTubeLine.name = lineName;
    }
    
    if ([elementName isEqualToString:@"Status"]) {
        NSString * status = [attributeDict objectForKey:@"Description"];
        self.currentTubeLine.statusCode = status;
    }    
}

//This method gets called for every closing XML tag.

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    
    //This close tag will signify the end of line information.
    //at this point we take the line object, add it to our collection of line objects and prepare for the next one.
    
    if ([elementName isEqualToString:@"LineStatus"]) {
        [self.tubeLineArray addObject:self.currentTubeLine];
        currentTubeLine = nil;
    }
    
}



@end
